package com.ycsj.goldmedalnewconcept.activity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.picasso.Picasso;
import com.ycsj.goldmedalnewconcept.adapter.UserQuanziAdapter;
import com.ycsj.goldmedalnewconcept.bean.QuanziResponse;
import com.ycsj.goldmedalnewconcept.bean.QuanziResponse.CircleInfo;
import com.ycsj.goldmedalnewconcept.bean.QuanziResponse.Friendlist;
import com.ycsj.goldmedalnewconcept.constant.Constant;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.view.PullToRefreshLayout;
import com.ycsj.goldmedalnewconcept.view.RoundImageView;
import com.ycsj.goldmedalnewconcept.R;

//个人相册（圈子）
@SuppressLint("HandlerLeak")
public class UserQuanziActivity extends Activity implements OnRefreshListener,
		OnClickListener {
	private List<ImageView> mImageViewList;
	private int[] images = { R.drawable.b1, R.drawable.temp, R.drawable.b2,
			R.drawable.b3, R.drawable.b4 };
	private int currentPosition = 1;
	private int dotPosition = 0;
	private int prePosition = 0;
	private LinearLayout mLinearLayoutDot;
	private List<ImageView> mImageViewDotList;
	private ListView lv_friends;
	private UserQuanziAdapter mAdapter;
	private ImageView iv_back;
	private ImageView iv_bg;
	private TextView tv_name;
	private RoundImageView mImageView;
	private PullToRefreshLayout refreshLayout;
	private String friendlist = "";
	private List<CircleInfo> list;
	private List<CircleInfo> list2;
	private List<Friendlist> list1;
	private String role; 
	private String role1; 
	private String account;
	private String c;
	private String name;
	private String headimg;
	private String circle_bgimg;
	private String update_date = "0";
	private int page = 0;
	private TextView loadTextView;
	private TextView tv_empty;
	private TextView tv_null;
	private TextView tv_title;
	private View footerView;
	private View loading;
	private boolean isLoading = false;
	private RotateAnimation loadingAnimation;
	private Intent intent;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_userquanzi);
		intent = getIntent();
		c = intent.getStringExtra("c");
		role1 = intent.getStringExtra("role");
		name = intent.getStringExtra("name");
		headimg = intent.getStringExtra("headimg");
		
//		Log.e("test", "c"+c);
//		Log.e("test", "role1"+role1);
//		Log.e("test", "name"+name);
//		Log.e("test", "headimg"+headimg);
		friendlist = SPUtil.getString(getBaseContext(), "friendlistjson", "");
		role = SPUtil.getString(this, "role", "");
		account = SPUtil.getString(this, "account", "");

		list = new ArrayList<CircleInfo>();
		list2 = new ArrayList<CircleInfo>();

		loadingAnimation = (RotateAnimation) AnimationUtils.loadAnimation(
				this, R.anim.rotating);
		// 添加匀速转动动画
		LinearInterpolator lir = new LinearInterpolator();
		loadingAnimation.setInterpolator(lir);
		
		initView();
		setOnListener();
		initData();
	}


	private void initView() {

		lv_friends = (ListView) findViewById(R.id.lv_friends);
		iv_back = (ImageView) findViewById(R.id.iv_back);
		refreshLayout = (PullToRefreshLayout) findViewById(R.id.refresh_view);
		tv_title = (TextView) findViewById(R.id.tv_title);
		tv_null = (TextView) findViewById(R.id.tv_null); 
		if(name!=null&&!"".equals(name)){
			tv_title.setText(name);
		}else{
			tv_title.setText("个人相册");
		}
		
		View headerView = LayoutInflater.from(getBaseContext()).inflate(
				R.layout.myquanzi_header, null);
		iv_bg = (ImageView) headerView.findViewById(R.id.iv_bg); // 顶部背景图
		tv_name = (TextView) headerView.findViewById(R.id.tv_name); // 顶部昵称
		
		mImageView = (RoundImageView) headerView.findViewById(R.id.mImageView); // 顶部头像

		lv_friends.addHeaderView(headerView);
		
		footerView = this.getLayoutInflater().inflate(
				R.layout.load_more_jpstar, null);
		loading = footerView.findViewById(R.id.loading_icon);
		loadTextView = (TextView) footerView.findViewById(R.id.loadmore_tv);
		tv_empty = (TextView) footerView.findViewById(R.id.tv_empty);
		lv_friends.addFooterView(footerView, null, false);
		footerView.setOnClickListener(this);
		mImageView.setOnClickListener(this);
		
		
		
	}

	private void setOnListener() {
		refreshLayout.setOnRefreshListener(this);

		iv_back.setOnClickListener(this);
		iv_bg.setOnClickListener(this);
	}	

	private void initData() {

		OkHttpClient mOkHttpClient = new OkHttpClient();
		FormEncodingBuilder builder = new FormEncodingBuilder();
		builder.add("type", "2");
		builder.add("c", c);
		builder.add("role", role1);
		builder.add("page", page+"");
		builder.add("friendlist", friendlist);
		builder.add("c2", account);
		builder.add("role2", role);
		builder.add("update_date", update_date);
		Request request = new Request.Builder()
				.url(Constant.SERVER_LOC + "CircleMsg").post(builder.build())
				.build();
		mOkHttpClient.newCall(request).enqueue(new Callback() {

//http://192.168.0.198:8888/ycsj_platform/CircleMsg?type=10&c=15333838051&role=2&friendlist=&c2=15333838051&role2=2&update_date=0&page=0
			@Override
			public void onFailure(Request arg0, IOException arg1) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						Toast.makeText(getBaseContext(), "网络无响应，请检查网络连接", 0)
								.show();
					}
				});
			}

			@Override
			public void onResponse(Response arg0) throws IOException {
				// 解析Json数据，保存登录状态及身份信息

				Gson gson = new Gson();
				String json = arg0.body().string();
				Log.e("testttt", json);
				QuanziResponse fromJson = gson.fromJson(json,
						QuanziResponse.class);

				if (fromJson != null) {
					if ("-1".equals(fromJson.state)
							|| "0".equals(fromJson.state)) {
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								
								if(page==0){
									
								}
								loading.setVisibility(loading.GONE);
								loading.clearAnimation();
								loadTextView.setText("已经是最后一条了");
								loadTextView.setClickable(false);
								isLoading = true;
								page = 0;
								tv_null
								 .setVisibility(tv_null.VISIBLE);
							}
						});
					} else if ("1".equals(fromJson.state)) {
						
						
						list2 = fromJson.circlelist;
						if(page==0){
							list = list2;
						}else{
							list.addAll(list2);
						}
						
						circle_bgimg = fromJson.circle_bgimg;
						update_date = fromJson.circlelist.get(fromJson.circlelist.size()-1).update_date;
						list1 = fromJson.friendlist;
						if (fromJson != null && fromJson.friendlist != null) {
							String friendlistjson = gson
									.toJson(fromJson.friendlist);
							SPUtil.putString(UserQuanziActivity.this,
									"friendlistjson", friendlistjson);
							
						}

						
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								
								refreshLayout
											.refreshFinish(PullToRefreshLayout.REFRESH_SUCCEED);
								mAdapter = new UserQuanziAdapter(
										UserQuanziActivity.this, list);
								if(page==0){
									
									lv_friends.setAdapter(mAdapter);
								}else{
									runOnUiThread(new Runnable() {
										@Override
										public void run() {
											mAdapter.notifyDataSetChanged();
										}
									});
								}
								loading.setVisibility(loading.GONE);
								loading.clearAnimation();
								if(list2.size()<5){
									loadTextView.setText("已经是最后一条了");
									loadTextView.setClickable(false);
									isLoading = true;
									page = 0;
								}else{
									loadTextView.setText("加载更多");
									isLoading = false;
								}

								Picasso.with(UserQuanziActivity.this)
										.load(circle_bgimg).into(iv_bg);

								if(headimg!=null&!"".equals(headimg)){
									Picasso.with(UserQuanziActivity.this)
									.load(headimg).into(mImageView);
								}
								
								if(name!=null&!"".equals(name)){
									tv_name.setText(name);
								}
							}
						});
					}
				}
			}
		});

		// EvaluationItem item = new EvaluationItem();
		// list.add(item);

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.iv_back:
			finish();
			break;
		case R.id.mImageView:// 顶部头像
			Intent intent5 = new Intent(UserQuanziActivity.this,
			UserInfoActivity.class);
			intent5.putExtra("c",c);
			intent5.putExtra("role",role1);
			startActivity(intent5);
			finish();
			break;
		case R.id.tv_newquanzi:
			Intent intent = new Intent(this, QuanziCreatActivity.class);
			startActivity(intent);
			break;
		case R.id.loadmore_layout:
			if (!isLoading) {
				loading.setVisibility(View.VISIBLE);
				loading.startAnimation(loadingAnimation);
				loadTextView.setText("正在加载...");
				isLoading = true;
				page++;
				initData();
			}
			break;
		}
	}

	@Override
	public void onRefresh() {
		// 下拉刷新操作
		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				page = 0;
				update_date = "0";
				initData();
				loadTextView.setText("加载更多");
				loading.setVisibility(View.GONE);
				isLoading = false;
				
			}
		}, 500);
	}

}
